package com.aiju.cash.ui.pay.manager;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.widget.TextView;

import com.aiju.app.DataProviderManager;
import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseActivity;
import com.aiju.cash.core.api.PrintApi;
import com.aiju.cash.ui.pay.entity.Detail;
import com.aiju.cash.ui.pay.entity.PrintData;
import com.aiju.cash.util.GsonHelper;
import com.aiju.cash.util.PhoneUtil;
import com.aiju.common.thread.AsyncExecutor;
import com.aiju.utils.DateUtil;
import com.aiju.utils.L;
import com.aiju.utils.PreferencesUtils;
import com.aiju.utils.PriceUtil;
import com.aiju.utils.T;
import com.aiju.widgit.dialog.MemberDialog;

import java.util.List;
import java.util.concurrent.Executor;

import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

/**
 * @author: 佐为
 * @date: 2017-04-19 10:38
 * @version: V1.0
 * @Description: 订单打印服务
 */
public class PrintManager {

    private int sum; //打印次数

    private IWoyouService woyouService; //商米打印服务

    private ICallback callback = null; //商米打印回调

    private Executor executor; //线程池

    private TextView textView; //显示打印状态

    private BaseActivity mContext; //context

    private String currentDate; //打印当前时间

    private List<Detail> goods; //商品详情列表

    private static volatile PrintManager instance; //单例

    private Handler handler = new Handler(Looper.getMainLooper());

    /**
     * 打印回调
     */
    public interface PrintCallBack {
        /**
         * 打印成功
         */
        void onPrintSuccess();

        /**
         * 打印失败
         */
        void onPrintFailure(String msg);
    }

    public static PrintManager getInstance() {
        if (instance == null) {
            synchronized (PrintManager.class) {
                if (instance == null) {
                    instance = new PrintManager();
                }
            }
        }
        return instance;
    }

    /**
     * 连接商米打印服务（AIDL）
     */
    private ServiceConnection connService = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            woyouService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            woyouService = IWoyouService.Stub.asInterface(service);
        }
    };

    private PrintManager() {
        this.executor = AsyncExecutor.createTaskDistributor();
        this.callback = new ICallback.Stub() {

            @Override
            public void onRunResult(final boolean success) throws RemoteException {
                L.d("onRunResult" + String.valueOf(success));
                if (textView != null) {
                    if (success) {
                        textView.setText("打印成功");
                    } else {
                        textView.setText("打印失败");
                    }
                }
            }

            @Override
            public void onReturnString(final String value) throws RemoteException {
                L.d("onReturnString:" + value + "\n");
            }

            @Override
            public void onRaiseException(int code, final String msg) throws RemoteException {
                L.d("onRaiseException: " + msg);
                if (textView != null) {
                    textView.setText("打印失败");
                }
            }
        };
    }

    /**
     * 绑定打印服务
     *
     * @param context 绑定的context对象
     */
    public void bindPrintService(BaseActivity context) {
        this.mContext = context;
        Intent intent = new Intent();
        intent.setPackage("woyou.aidlservice.jiuiv5");
        intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
        context.startService(intent);
        context.bindService(intent, connService, Context.BIND_AUTO_CREATE);
    }

    /**
     * 打印小票
     *
     * @param context   调用页面
     * @param serialNum 小票号
     * @param callBack  打印回调
     */
    public void printReceipt(final BaseActivity context, final String serialNum, final PrintCallBack callBack) {
        this.mContext = context;
        this.currentDate = DateUtil.getCurrentDate(DateUtil.dateFormatYMDHMS);
        if (isSUNMI()) {
            this.sum = PreferencesUtils.getInt(DataProviderManager.getContext(), "printSum", 1);
            new PrintApi(mContext.getDialogHelper()).getprintcontent(serialNum, new SimpleHttpCallback() {
                @Override
                protected void onDataSuccess(String data) {
                    printSUNMI(GsonHelper.convertEntity(data, PrintData.class), callBack);
                }

                @Override
                protected void onDataFailure(int code, String msg) {
                    if (code == 404) {
                        show404Dialog();
                    } else {
                        if (callBack != null) {
                            callBack.onPrintFailure(msg);
                        }
                    }
                }
            });
        } else {
            print365(serialNum, callBack);
        }
    }

    /**
     * 365小票机打印
     *
     * @param serialNum 小票号
     * @param callBack  打印回调
     */
    private void print365(final String serialNum, final PrintCallBack callBack) {
        new PrintApi(mContext.getDialogHelper()).print(serialNum, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                if (callBack != null) {
                    callBack.onPrintSuccess();
                }
            }

            @Override
            protected void onDataFailure(int code, String msg) {
                if (code == 404) {
                    show404Dialog();
                } else {
                    if (callBack != null) {
                        callBack.onPrintFailure(msg);
                    }
                }
            }
        });
    }

    /**
     * 显示设备不在线
     */
    private void show404Dialog() {
        new MemberDialog(mContext)
                .setTitileText("打印功能需要小票机的支持")
                .setMsgText("很抱歉，未检测到您的小票机，暂时无法打印，请联系客服处理")
                .setRightText("联系客服")
                .setLeftText("取消")
                .setLayoutParams()
                .setOnSimpleClick(new MemberDialog.OnSimpleClick() {
                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onSubmit() {
                        PhoneUtil.contactUs(mContext);
                    }
                })
                .show();
    }

    /**
     * 打印成功更新打印状态(只有商米调用此方法)
     *
     * @param printCallBack
     */
    private void successPrint(final PrintData printData, final PrintCallBack printCallBack) {
        new PrintApi(mContext.getDialogHelper()).updateprintstatus(printData.getSerialNum(), printData.getNo(), currentDate, printData.getPrintSerial(), new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                T.ToastShort("小票已打印");
                if (printCallBack != null) {
                    printCallBack.onPrintSuccess();
                }
            }

            @Override
            protected void onDataFailure(int code, String msg) {
                T.ToastShort("更新打印状态失败");
            }
        });
    }

    /**
     * 商米设备打印小票
     *
     * @param pay           打印实体数据
     * @param printCallBack 打印回调
     */
    private void printSUNMI(final PrintData pay, final PrintCallBack printCallBack) {
        if (pay == null) {
            T.ToastShort("未查找到相应订单信息");
            return;
        }
        goods = pay.getDetailList();
        final String titleNumber = "====== No." + pay.getNo() + "小票 ======\n\n";
        final String titleNumberEnd = "====== No." + pay.getNo() + "小票完 ====== \n\n";
        final String storeName = pay.getShopName() + "\n\n";
        final String time = "时  间：" + DateUtil.getStringByFormat(currentDate, DateUtil.dateFormatYMDHMS_P) + "\n";
        final String operatorName = "收银员：" + pay.getOperatorId() + "\n\n";
        // final String noteNumber = "流水号：" + pay.getSerialNum() + "\n\n";
        final String columnName = "品名=========数量======小计\n\n";
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    woyouService.setAlignment(1, callback);//设置居中
                    woyouService.setFontSize(26, callback);
                    woyouService.getPrinterSerialNo();
                    woyouService.getPrinterVersion();

                    woyouService.printTextWithFont(titleNumber, "", 28, callback);//小票编号
                    woyouService.printTextWithFont(storeName, "", 36, callback);//店铺名称

                    woyouService.setAlignment(0, callback);
                    woyouService.printText(time, callback);//时间
                    woyouService.printText(operatorName, callback);//操作员
                    //woyouService.printText(noteNumber, callback);//流水号

                    woyouService.printTextWithFont(columnName, "", 28, callback);

                    String[] text = new String[2];
                    int[] width = new int[]{17, 11};

                    for (int i = 0; i < goods.size(); i++) {
                        Detail good = goods.get(i);
                        woyouService.printText(good.getGoodsName() + "\n", callback);//商品名
                        if (good.getUnit().equals("件")) {
                            text[0] = "x" + String.valueOf(good.getNum());
                            text[1] = good.getSum();
                        } else {
                            if (good.getUnit().equals("500克")) {
                                text[0] = good.getNum() + "克";
                            } else {
                                text[0] = good.getNum() + good.getUnit();
                            }
                            text[1] = PriceUtil.formatDouble(good.getSum());
                        }
                        woyouService.printColumnsText(text, width, new int[]{2, 2}, callback);
                    }
                    woyouService.printText("=============================\n", callback);

                    String[] text2 = new String[3];
                    text2[0] = "合计";
                    text2[1] = "共" + pay.getTotalcount() + "件";
                    text2[2] = "￥" + pay.getTotalsum();
                    woyouService.printColumnsText(text2, new int[]{4, 13, 11}, new int[]{0, 2, 2}, callback);
                    lin(26);

                    text[0] = "优惠类型";
                    text[1] = pay.getYouhuiType();
                    woyouService.printColumnsText(text, new int[]{14, 14}, new int[]{0, 2}, callback);

                    text[0] = "优惠金额";
                    text[1] = "-￥" + pay.getYouhuiSum();
                    woyouService.printColumnsText(text, new int[]{14, 14}, new int[]{0, 2}, callback);

                    lin(26);
                    text[0] = "应收金额";
                    text[1] = "￥" + pay.getYingshouSum();
                    woyouService.printColumnsText(text, new int[]{14, 14}, new int[]{0, 2}, callback);

                    text[0] = "实收金额";
                    text[1] = "￥" + pay.getShijiSum();
                    woyouService.printColumnsText(text, new int[]{14, 14}, new int[]{0, 2}, callback);

                    text[0] = "找零";
                    text[1] = "￥" + pay.getGetChange();
                    woyouService.printColumnsText(text, new int[]{14, 14}, new int[]{0, 2}, callback);

                    woyouService.printText("=============================\n", callback);

                    woyouService.setAlignment(1, callback);
                    woyouService.printTextWithFont("谢谢惠顾，欢迎常来！\n", "", 30, callback);
                    woyouService.printText("爱聚收银提供技术支持\n", callback);
                    woyouService.printText("小票号（用于售后）\n", callback);

                    woyouService.printQRCode(pay.getPrintSerial(), 5, 2, callback);
                    woyouService.printText(pay.getPrintSerial() + "\n", callback);

                    woyouService.printTextWithFont(titleNumberEnd, "", 28, callback);//小票编号
                    woyouService.lineWrap(3, callback);

                    sum--;
                    if (sum == 0) {
                        sum = PreferencesUtils.getInt(DataProviderManager.getContext(), "printSum", 1);
                        successPrint(pay, printCallBack);
                    } else {
                        printSUNMI(pay, printCallBack);
                    }

                } catch (RemoteException e) {
                    if (printCallBack != null) {
                        printCallBack.onPrintFailure("小票打印出现异常");
                    }
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 打印换行
     *
     * @param size
     */
    private void lin(int size) {
        try {
            woyouService.printTextWithFont("\n", "", size, callback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否是商米设备
     *
     * @return
     */
    public boolean isSUNMI() {
        return DataProviderManager.getDataProvider().getModel().equals("V1");
    }

    public TextView getTextView() {
        return textView;
    }

    public void setTextView(TextView textView) {
        this.textView = textView;
    }
}
